package tech.yunland.shop.domain.service;

import com.moyuer.bsf.domain.model.Organ;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.yunland.shop.domain.dao.DormitoriesDao;
import tech.yunland.shop.domain.dao.OrganDormitoriesDao;
import tech.yunland.shop.domain.model.Dormitories;
import tech.yunland.shop.domain.model.OrganDormitories;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

/**
 * Created by v on 17-7-3.
 */
@Service
public class DormitoriesServiceImpl implements DormitoriesService {

    @Autowired
    private DormitoriesDao dormitoriesDao;

    @Autowired
    private OrganDormitoriesDao organDormitoriesDao;

    @Override
    public void save(Dormitories dormitories, Organ primaryOrgan) {
        dormitoriesDao.save(dormitories);
        OrganDormitories organDormitories = new OrganDormitories();
        organDormitories.setDormitories(dormitories);
        organDormitories.setOrgan(primaryOrgan);
        organDormitoriesDao.save(organDormitories);
    }

    @Override
    public Integer getSize(String param, List<String> organIds) {
        String strOrginIds = StringUtils.join(organIds, "','");
        String sql =
                "select count(1) counts\n" +
                        "FROM dormitories d LEFT JOIN organ_dormitories od ON d.id = od.dormitories_id\n" +
                        "WHERE d.id IN (SELECT od.dormitories_id\n" +
                        "               FROM organ_dormitories od\n" +
                        "               WHERE od.organ_id in('" + strOrginIds + "'))";
        if (param != null) {
            sql += " and d.dname like '%" + param + "%'";
        }
        int counts = ((BigInteger) dormitoriesDao.findUniqueBySQL(sql).get("counts")).intValue();
        return counts;
    }

    @Override
    public List<Map<String, Object>> get(String param, Integer startIdx, Integer rows, List<String> organIds) {
        String strOrginIds = StringUtils.join(organIds, "','");
        String sql =
                "SELECT\n" +
                        "  d.id,\n" +
                        "  d.create_time,\n" +
                        "  d.dname,\n" +
                        "  d.quantity,\n" +
                        "  d.size,\n" +
                        "  od.organ_id,\n" +
                        "  od.id odid\n" +
                        "FROM dormitories d LEFT JOIN organ_dormitories od ON d.id = od.dormitories_id\n" +
                        "WHERE d.id IN (SELECT od.dormitories_id\n" +
                        "               FROM organ_dormitories od\n" +
                        "               WHERE od.organ_id in('" + strOrginIds + "'))";
        if (param != null) {
            sql += " and d.dname like '%" + param + "%'";
        }
        return dormitoriesDao.findBySQL(sql, startIdx, rows);
    }
}
